package com.liming.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liming.common.constant.LockConstants;
import com.liming.common.enums.*;
import com.liming.common.exception.BusinessException;
import com.liming.common.pojo.dto.order.admin.RefundPageQuery;
import com.liming.common.pojo.dto.order.user.ApplyRefundDTO;
import com.liming.common.pojo.entity.BaseEntity;
import com.liming.common.pojo.entity.order.Order;
import com.liming.common.pojo.entity.order.RefundOrder;
import com.liming.common.pojo.vo.PageVO;
import com.liming.common.pojo.vo.order.web.RefundOrderVO;
import com.liming.common.util.BeanUtils;
import com.liming.common.util.OrderUtils;
import com.liming.common.util.PageUtils;
import com.liming.common.util.mybatisplus.MPUtil;
import com.liming.order.mapper.RefundOrderMapper;
import com.liming.order.service.OrderMircoService;
import com.liming.order.service.RefundOrderMircoService;
import com.liming.service.redisson.RLocker;
import com.liming.service.wx.WxClient;
import com.liming.stock.client.StockClient;
import com.wechat.pay.java.service.refund.model.Refund;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author liming
 * @date 2025/4/14
 */
@Slf4j
@Service
@AllArgsConstructor
public class RefundOrderMircoServiceImpl extends ServiceImpl<RefundOrderMapper, RefundOrder>
        implements RefundOrderMircoService, MPUtil<RefundOrder> {

    private final WxClient wxClient;
    private final RLocker locker;
    @Lazy
    private final OrderMircoService orderMircoService;
    private final StockClient stockClient;

    @Override
    public void judgeHaveRefund(Long id) {
        // 一笔订单 不可以一下子申请多次退款
        // 判断该订单是否存在 退款申请?
        lambdaQuery()
                .eq(RefundOrder::getOrderId, id)
                .oneOpt()
                .ifPresent(refundOrder -> {
                    if (ObjectUtil.equal(refundOrder.getApplyStatus(), RefundApplyStatusEnum.MERCHANT_REFUSE.getCode())) {
                        String rejectReason = refundOrder.getRejectReason();
                        throw new BusinessException("商家已经拒绝您的请求过啦 " + " 原因: " + rejectReason);
                    }
                    String msg = RefundApplyStatusEnum.getMessageByCode(refundOrder.getApplyStatus());
                    throw new BusinessException("您已经申请过该笔订单退款咯~ 请麻烦等待, 当前状态: " + msg);
                });
    }

    @Override
    public void applyRefund(ApplyRefundDTO dto) {
        RefundOrder save = BeanUtils.toBean(dto, RefundOrder.class);
        save.setApplyStatus(RefundApplyStatusEnum.USER_APPLY.getCode());
        Assert.isTrue(save(save), () -> new RuntimeException("申请退款失败"));
    }

    @Override
    public PageVO<RefundOrderVO> refundPage(RefundPageQuery query) {
        IPage<RefundOrder> rawPage = lambdaQuery()
                .like(StrUtil.isNotBlank(query.getOrderNo()), RefundOrder::getOrderNo, query.getOrderNo())
                .like(StrUtil.isNotBlank(query.getRefundNo()), RefundOrder::getRefundNo, query.getRefundNo())
                .like(StrUtil.isNotBlank(query.getUsername()), RefundOrder::getUsername, query.getUsername())
                .eq(ObjectUtil.isNotNull(query.getApplyStatus()), RefundOrder::getApplyStatus, query.getApplyStatus())
                .eq(ObjectUtil.isNotNull(query.getStatus()), RefundOrder::getStatus, query.getStatus())
                .orderByDesc(BaseEntity::getCreateTime)
                .page(setPage(query));
        return PageUtils.convert(rawPage, refundOrder -> BeanUtils.toBean(refundOrder, RefundOrderVO.class));
    }

    @Override
    @GlobalTransactional
    public Boolean agreeRefund(Long refundOrderId) {
        // 判断退款单是否可以同意退款
        RefundOrder refundOrder = getById(refundOrderId);
        Assert.equals(RefundApplyStatusEnum.USER_APPLY.getCode(), refundOrder.getApplyStatus(), () -> new BusinessException("退款订单申请状态异常 - 不可修改"));
        // 生成退款订单号
        String refundNo = OrderUtils.refundOrderNo();
        // 微信申请退款
        Refund wxRefund = wxClient.wxRefundWithRefundNoByOrderNo(refundOrder.getOrderNo(), refundNo);
        updateRefundInfoByWxRefund(refundOrderId, wxRefund, refundNo);
        return true;
    }

    private void updateRefundInfoByWxRefund(Long refundOrderId, Refund wxRefund, String refundNo) {
        String refundId = wxRefund.getRefundId();
        String channel = wxRefund.getChannel().toString();
        String userReceivedAccount = wxRefund.getUserReceivedAccount();
        String strStatus = wxRefund.getStatus().toString();
        String fundsAccount = wxRefund.getFundsAccount().toString();
        // 退款成功时间
        // 修改系统退款订单状态
        RefundOrder updateRefundOrder = new RefundOrder();
        updateRefundOrder.setId(refundOrderId);
        updateRefundOrder.setRefundNo(refundNo);
        updateRefundOrder.setApplyStatus(RefundApplyStatusEnum.MERCHANT_AGREE.getCode());
        updateRefundOrder.setRefundId(refundId);
        updateRefundOrder.setChannel(RefundChannelEnum.getCodeByName(channel));
        updateRefundOrder.setUserReceivedAccount(userReceivedAccount);
        updateRefundOrder.setStatus(RefundStatusEnum.getCodeByName(strStatus));
        updateRefundOrder.setFundsAccount(RefundAccountEnum.getCodeByName(fundsAccount));
        String successTime = wxRefund.getSuccessTime();
        if (StrUtil.isNotBlank(successTime)) {
            LocalDateTime updateTime = LocalDateTime.parse(successTime, DateTimeFormatter.ISO_ZONED_DATE_TIME);
            updateRefundOrder.setUpdateTime(updateTime);
        }
        Assert.isTrue(updateById(updateRefundOrder), () -> new BusinessException("更新退款订单失败"));
    }

    @Override
    @Transactional
    public Boolean refuseRefund(Long refundOrderId, String reason) {
        // 商家拒绝退款
        // 修改系统订单状态（已支付）
        RefundOrder refundOrder = getById(refundOrderId);
        Order updateOrderStatus = new Order();
        updateOrderStatus.setId(refundOrder.getOrderId());
        updateOrderStatus.setStatus(OrderStatusEnum.PAID.getCode());
        Assert.isTrue(orderMircoService.updateById(updateOrderStatus), () -> new BusinessException("更新订单状态失败"));
        RefundOrder update = new RefundOrder();
        update.setId(refundOrderId);
        update.setApplyStatus(RefundApplyStatusEnum.MERCHANT_REFUSE.getCode());
        update.setRejectReason(reason);
        Assert.isTrue(updateById(update), () -> new BusinessException("更新退款订单失败"));
        return true;
    }

    @Override
    public Boolean queryRefund(Long refundOrderId) {
        RefundOrder refundOrder = getById(refundOrderId);
        String refundNo = refundOrder.getRefundNo();
        Refund wxRefund = wxClient.wxRefundQueryByRefundNo(refundNo);
        updateRefundInfoByWxRefund(refundOrderId, wxRefund, null);
        Long orderId = refundOrder.getOrderId();
        if (Objects.equals(RefundStatusEnum.getCodeByName(wxRefund.getStatus().toString()), RefundStatusEnum.SUCCESS.getCode()) &&
                Objects.equals(refundOrder.getStatus(), RefundStatusEnum.PROCESSING.getCode())) {
            // 如果查询退款成功了，修改系统订单状态为已退款
            orderMircoService.refundSuccess(orderId);
            // 更新库存流水 （库存增加 - 插入退款库存流水 ）
            stockClient.refundSuccess(orderId);
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean userApplyRefund(Long id, String reason) {
        String lockKey = LockConstants.LOCK_REFUND + id;
        try {
            if (locker.tryLock(lockKey, 0, 1, TimeUnit.MILLISECONDS)) {
                // 判断是否已经申请退款
                judgeHaveRefund(id);
                // 判断订单状态是否可以退款
                // 已支付、待发货、待自提 可以退款 （其他状态不可以退款）
                Order order = orderMircoService.getById(id);
                Assert.isTrue(CollUtil.contains(OrderStatusEnum.canRefund(), order.getStatus()), () -> new BusinessException("订单状态异常 - 不可退款"));
                // 用户申请退款时，直接修改系统订单状态（待退款）
                Long orderId = order.getId();
                Order updateOrderStatus = new Order();
                updateOrderStatus.setId(orderId);
                updateOrderStatus.setStatus(OrderStatusEnum.UN_REFUNDED.getCode());
                Assert.isTrue(orderMircoService.updateById(updateOrderStatus), () -> new BusinessException("更新订单状态失败"));
                // 插入申请退款
                ApplyRefundDTO dto = new ApplyRefundDTO();
                dto.setOrderId(id);
                dto.setOrderNo(order.getOrderNo());
                dto.setUsername(order.getUsername());
                dto.setReason(reason);
                applyRefund(dto);
                return true;
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        } finally {
            locker.unlock(lockKey);
        }
        return false;
    }

    @Override
    public RefundOrderVO refundDetail(Long orderId) {
        RefundOrder oldRefund = lambdaQuery().eq(RefundOrder::getOrderId, orderId).one();
        Assert.notNull(oldRefund, () -> new BusinessException("退款订单不存在"));
        Long id = oldRefund.getId();
        if (StrUtil.isNotBlank(oldRefund.getRefundNo())) {
            queryRefund(id);
        }
        RefundOrder newRefund = getById(id);
        return BeanUtils.toBean(newRefund, RefundOrderVO.class);
    }
}
